package team.scau.laboratory_repair.common.shiro;

import lombok.extern.apachecommons.CommonsLog;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import team.scau.laboratory_repair.common.constant.ConstantRole;
import team.scau.laboratory_repair.modules.po.Perm;
import team.scau.laboratory_repair.modules.po.Role;
import team.scau.laboratory_repair.modules.po.User;
import team.scau.laboratory_repair.service.PermService;
import team.scau.laboratory_repair.service.RoleService;
import team.scau.laboratory_repair.service.UserService;

import java.util.List;

/**
 * @author 30254
 * creadtedate:2018/8/17
 */
@Component
@CommonsLog
public class AdminUserRealm extends AuthorizingRealm {

    @Autowired
    private UserService userService;
    @Autowired
    private RoleService roleService;
    @Autowired
    private PermService permService;

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        //获取登录时输入的用户名
        String loginName = (String) principals.fromRealm(getName()).iterator().next();
        if (StringUtils.isBlank(loginName)) {
            return null;
        }
        User user;

        try {
            user = userService.getByAccount(loginName);
        } catch (Exception e) {
            user = null;
        }
        if (user != null) {
            try{
                SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
                //权限信息对象info,用来存放查出的用户的所有的角色（role）及权限（perm）
                if(user.getRole().equals(ConstantRole.ROLE_SUPER)){
                    //超级管理获得所有权限
                    List<Perm> perms = permService.list();
                    perms.forEach(perm -> {
                        if(StringUtils.isNotEmpty(perm.getPerm())){
                            info.addStringPermission(perm.getPerm());
                        }
                    });
                }else {
                    Role role = roleService.findById(user.getRole());
                    String[] permIds = role.getPerm().split(",");
                    for(String permId:permIds){
                        Perm perm = permService.findById(Long.valueOf(permId));
                        if(perm != null && StringUtils.isNotEmpty(perm.getPerm())){
                            info.addStringPermission(perm.getPerm());
                        }
                    }
                }
                return info;
            }catch (Exception e){
                e.printStackTrace();
                log.error(e.getMessage(), e);
                return null;
            }
        }
        return null;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        UserToken token = (UserToken) authenticationToken;
        //查出是否有此用户
        User user;
        try {
            user = userService.getByAccount(token.getUsername());
        } catch (Exception e) {
            e.printStackTrace();
            log.error(e.getMessage(), e);
            user = null;
        }
        if (user == null) {
            //错误的帐号，没有这个账号
            throw new UnknownAccountException("账号或者密码错误");
        }
        if (!user.getPassword().equals(new String(token.getPassword()))) {
            throw new IncorrectCredentialsException("账号或者密码错误");
        }

        //若存在，将此用户存放到登录认证info中
        return new SimpleAuthenticationInfo(user.getAccount(), user.getPassword().toUpperCase(), getName());

    }
}
